<template>
  <div class="L-form-container">

    <!-- 表头 -->
    <div v-for="(item, index) in jsondata.head" :key="index" style="margin-bottom:30px">
      <van-cell-group inset>
        <div class="L-form-title-row" @click="item.expand = !item.expand">
          <div>
            <i class="iconfont icon-yuanzhu" style="color:#1683f7"></i>
            <span class="L-text L-primary-text-color">{{ item.grouptitle }}</span>
          </div>
          <i class="iconfont" :class="item.expand ? 'icon-zhankai1' : 'icon-xiayibu2'"></i>
        </div>
        <template v-if="item.expand">
          <FormInput v-for="(fitem, findex) in item.groupvalue" :key="findex" :formItem="fitem"
            @handleChange="handleChange" @handleClear="(e1,e2,e3) => formHooks.handleClear(e1,e2,e3,fitem)" tableType="head"
            :handleShowNumberKeyboardSpace="handleShowNumberKeyboardSpace" :handleSelectedSlor="handleSelectedSlor"
            :jsondata="jsondata"></FormInput>
        </template>
      </van-cell-group>
    </div>

    <!-- 表体 -->
    <div v-if="hasdetail === '1'">
      <!-- 子表table显示 -->
      <template v-if="bodyShowType === 'row'">
        <div v-for="(itembody, indexName) in jsondata.bodydata" :key="indexName">
          <div class="L-form-title-row" style="width: 98%;">
            <div>
              <i class="iconfont icon-yuanzhu" style="color:#1683f7"></i>
              <span class="L-text L-primary-text-color">{{ indexName }}</span>
            </div>
            <span v-if="sdCanAddBodyRow" style="color:#1683f7" @click="handleAddBodyData(indexName)"> + 添加一行</span>
          </div>

          <vxe-table :data="jsondata.bodydata[indexName]">
            <vxe-column type="seq" width="50"></vxe-column>
            <vxe-column v-for="(itemdata, index) in jsondata.body[indexName]" :field="itemdata.sField"
              :title="itemdata.sTitle" width="180">

              <template #default="{ rowIndex, row }">

                <FormInput :formItem="row[index]" @handleChange="handleChange" @handleClear="formHooks.handleClear"
                  tableType="body" :bodyDataName="`${indexName}`" :bodyDataIndex="`${rowIndex}`"
                  :handleShowNumberKeyboardSpace="handleShowNumberKeyboardSpace" :jsondata="jsondata" inputStyle="v2">
                </FormInput>
              </template>
            </vxe-column>

            <vxe-column width="50" title="操作" fixed="right">
              <template #default="{ rowIndex }">
                <span @click="handleDeleteBodyData(indexName, rowIndex)">删除</span>
              </template>
            </vxe-column>
          </vxe-table>
        </div>

      </template>

      <!-- <template v-if="bodyShowType === 'row'">
        <div v-for="(itembody, indexName) in jsondata.bodydata" :key="indexName">
          <div class="L-form-title-row" style="width: 98%;">
            <div>
              <i class="iconfont icon-yuanzhu" style="color:#1683f7"></i>
              <span class="L-text L-primary-text-color">{{ indexName }}</span>
            </div>
            <span style="color:#1683f7" @click="handleAddBodyData(indexName)"> + 添加一行</span>
          </div>

          <div class="L-table">
         

            <div class="L-table-row" style="background-color:#fff" :key="rowIndex">
   

              <div v-for="(item, index) in jsondata.body[indexName]" :key="index">
                <div class="L-th">{{ item.sTitle }}</div>
                <div class="L-td" v-for="(rowItem, rowIndex) in itembody" :key="rowIndex">
                  <FormInput :formItem="rowItem[index]" @handleChange="handleChange" @handleClear="formHooks.handleClear"
                    tableType="body" :bodyDataName="`${indexName}`" :bodyDataIndex="`${rowIndex}`"
                    :handleShowNumberKeyboardSpace="handleShowNumberKeyboardSpace" :jsondata="jsondata" inputStyle="v2">
                  </FormInput>

                </div>
              </div>
              <div>
                <div class="L-th" style="width: 70px;">操作</div>
                <div class="L-td" style="width: 70px;" v-for="(rowItem, rowIndex) in itembody" :key="rowIndex">
                   <span @click="handleDeleteBodyData(indexName, rowIndex)">删除</span>
                </div>

              </div>
              


             


            </div>
          </div>

        </div>
      </template> -->

      <!-- 子表form显示 -->
      <template v-else>
        <div v-for="(itembody, indexName) in jsondata.bodydata" :key="indexName">
          <van-cell-group inset v-for="(item, index) in jsondata.bodydata[indexName]" :key="`${indexName}${index}`"
            class="L-margin-top-10">
            <div class="L-form-title-row" @click="item.expand = !item.expand">
              <div>
                <i class="iconfont icon-yuanzhu" style="color:#1683f7"></i>
                <span class="L-text L-primary-text-color">{{ indexName }} {{ index + 1 }}</span>
              </div>
              <i class="iconfont" :class="item.expand ? 'icon-zhankai1' : 'icon-xiayibu2'"></i>
            </div>
            <template v-if="item.expand">
              <FormInput v-for="(fitem, findex) in item" :key="findex" :formItem="fitem" @handleChange="handleChange"
                @handleClear="formHooks.handleClear" tableType="body" :bodyDataName="`${indexName}`"
                :bodyDataIndex="`${index}`" :jsondata="jsondata">
              </FormInput>
            </template>

            <div v-if="item.expand" style="text-align:center;color:red;margin:20px auto"
              @click="handleDeleteBodyData(indexName, index)">
              <i class="iconfont icon-shanchu1"></i>
              删除
              <!-- {{indexName}} {{index+1}} -->
            </div>

          </van-cell-group>

          <van-cell-group inset class="L-margin-top-20" v-if="sdCanAddBodyRow">
            <div class="L-text-align-center" @click="handleAddBodyData(indexName)"
              style="height: 45px;line-height: 45px;color:#1989fa"> + 增加明细</div>
          </van-cell-group>
        </div>
      </template>
    </div>

    <!-- <div style="height: 250px;" v-show="showNumberKeyboardSpace"></div> -->

  </div>



  <div class="L-bottom-space"></div>
  <van-sticky position="bottom">
    <div class="L-bottom-row">
      <div class="L-operate-btn" @click="callBack()">取消</div>
      <div class="L-operate-btn" @click="handleSave()">保存</div>
      <div class="L-operate-btn" v-if="isflow" @click="handleSave(true)">保存并提交</div>
    </div>
  </van-sticky>
</template>

<script setup lang="ts">

import { ref, onMounted } from "vue";
import { closeToast, showLoadingToast, showToast, showSuccessToast, showConfirmDialog } from "vant";
import { useRoute } from "vue-router";
const route = useRoute();
import FormInput from "@/components/base/Form/FormInput.vue";


// 引用表单hooks
import { useForm } from "@/hooks/formhooks.js";
const formHooks = useForm();



import router from "@/router/index";
import { apiConfigurable } from "@/request/api/api";
import emitter from "@/utils/emitter";

const activeNames = ref([]);
const props = defineProps({
  itemid: {
    type: [String, Array],
    default: "",
  },
  loadapi: String,
  loadParams: Object,
  submitapi: String,
  callBack: {
    type: Function,
    default: () => { },
  },
  mode: {
    type: String,
    default: "page",
  },
  idobject: {
    type: [String, Array],
    default: "",
  },
});

const bodyShowType = ref("colunm")

const isflow = ref(false)
const isLoading = ref(false);
const idtemplate = route.query.idtemplate || "";
const object_id = ref("")

import type { jsondataVO } from "@/interface/interface"
let jsondata = ref<jsondataVO>({});

const orginData = ref<jsondataVO>({});
const hasdetail = ref("")

const sdCanAddBodyRow = ref(true)

const bodydataExpandArr = ref({});

const showNumberKeyboardSpace = ref(false)
function handleShowNumberKeyboardSpace(val) {
  showNumberKeyboardSpace.value = val
}


onMounted(() => {
  getData();
});


function getData() {
  isLoading.value = true;
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });
  apiConfigurable(props.loadapi as string, props.loadParams, "post").then((res) => {
    if (res.code === 0) {
      isLoading.value = false;

      // 表头数据整理
      res.data.jsondata.head = res.data.jsondata.head.map((item) => {
        item.expand = true;
        return item;
      });

      jsondata.value = res.data.jsondata;
      hasdetail.value = res.data.jsondata?.hasdetail;
      object_id.value = res.data.jsondata[`${props.idobject}_id`] || ""



      // 是否可以提交至审批流
      isflow.value = res.data.isflow

      //子表是否横屏展示
      if (jsondata.value.headmetadata) {
        bodyShowType.value = jsondata.value.headmetadata?.lFlatDisplay ? "row" : "colunm"
      }

      //参照生单是否显示添加行
      if (jsondata.value.optionvalue) {
        sdCanAddBodyRow.value = jsondata.value.optionvalue !== '否' ? true : false
      }



      //字段联动
      orginData.value = JSON.parse(JSON.stringify(res.data.jsondata));
      controlLinkArr.value = getFieldLink(jsondata.value);

      closeToast();

    } else {
      setTimeout(() => {
        props.callBack()
      }, 1000)

    }

  }
  );
}

//字段联动hooks
import { useFieldLinkage } from "@/hooks/hooks.js";
const { controlLinkArr, getFieldLink, handleFiledLink } = useFieldLinkage();
//字段映射hooks
import { useFieldMap } from "@/hooks/hooks.js";
const { handleFiledMap } = useFieldMap();

// 字段值发生变化
function handleChange(item, value, valuehidden = "", fieldmap = {}, mapobject = "", tableType = "head", bodyDataName = "", bodyDataIndex = "") {
  item.value = value;
  // debugger
  // if (valuehidden) {
    item.valuehidden = valuehidden || '';
  // }
  //字段联动
  handleFiledLink(item, jsondata.value, orginData.value);

  //字段映射(和插入点)
  if (fieldmap && mapobject) {
    handleFiledMap(jsondata, fieldmap, mapobject, tableType, bodyDataName, bodyDataIndex);
  }
}



interface submitData {
  [name: string]: any;
}

// 保存
async function handleSave(isSubmit = false) {
  const data: submitData = {};
  const { idobject, itemid } = props;
  // data[idobject + "_id"] = jsondata.value[idobject + "_id"] || route.query.itemid;
  data[idobject + "_id"] = itemid ? itemid : object_id.value

  data[idobject + "_idtemplate"] = idtemplate;
  for (let groupindex in jsondata.value.head) {
    let itemgroup = jsondata.value.head[groupindex].groupvalue;
    for (let itemindex in itemgroup) {
      let itemdata = itemgroup[itemindex];
      if (!checkForm(itemdata)) {
        return;
      }
      if (itemdata.sUIType === "ref") {
        data[itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
        data[itemdata.idObject + "_" + itemdata.sField + "_ref"] = itemdata.value;
      } else if (itemdata.sUIType === "enum") {
        data[itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
        data[itemdata.idObject + "_" + itemdata.sField + "_enum"] = itemdata.value;
      } else if (
        itemdata.sUIType === "file" ||
        itemdata.sUIType === "picture"
      ) {
        data[itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
        data[itemdata.idObject + "_" + itemdata.sField + "_title"] = itemdata.value;
      } else {
        data[itemdata.idObject + "_" + itemdata.sField] = itemdata.value;
      }
    }
  }

  if (jsondata.value.hasdetail === "1") {
    for (let indexName in jsondata.value.bodydata) {
      for (let i = 0; i < jsondata.value.bodydata[indexName].length; i++) {
        let item = jsondata.value.bodydata[indexName][i];
        for (let itemindex in item) {
          let itemdata = item[itemindex];
          if (itemdata.sUIType === "ref") {
            data[i + "_" + itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
            data[i + "_" + itemdata.idObject + "_" + itemdata.sField + "_ref"] = itemdata.value;
          } else if (itemdata.sUIType === "enum") {
            data[i + "_" + itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
            data[i + "_" + itemdata.idObject + "_" + itemdata.sField + "_enum"] = itemdata.value;
          } else {
            data[i + "_" + itemdata.idObject + "_" + itemdata.sField] = itemdata.value;
          }
        }
      }
    }
  }

  showLoadingToast({
    message: "保存中...",
    forbidClick: true,
    duration: 0,
  });

  apiConfigurable(props.submitapi as string, data, "post").then(async (res) => {
    if (res.code === 0) {

      showSuccessToast("已保存");

      if (isflow.value && isSubmit) {
        showLoadingToast({
          message: "提交中...",
          forbidClick: true,
          duration: 0,
        });
        const flowRes = await handleFlowSubmit(data)
        if (flowRes.code === 0) {
          showSuccessToast("提交成功!");
        }
      }



      setTimeout(() => {
        closeToast();
        props.callBack();
      }, 1000)

    }
  });
}

//提交至审批流
function handleFlowSubmit(data) {
  const flowsubmitapi = `${props.submitapi.split('.')[0]}.flowsubmit.do`

  return apiConfigurable(flowsubmitapi as string, data, "post")
}


//提交
function checkForm(itemdata) {
  if (itemdata.lMustInput === "1" && itemdata.value === "") {
    showToast(`${itemdata.sTitle}不能为空`);
    return false;
  }
  return true;
}

function handleAddBodyData(bodyDataName: string | number) {
  const bodydataItem = JSON.parse(JSON.stringify(orginData.value?.body[bodyDataName]))
  jsondata.value?.bodydata[bodyDataName].push(bodydataItem)
}

function handleDeleteBodyData(bodyDataName: string | number, index: number) {
  if (jsondata.value?.bodydata[bodyDataName] && jsondata.value?.bodydata[bodyDataName].length === 1) {
    showToast("至少要保留一条表体数据!")
    return
  }

  showConfirmDialog({
    title: '标题',
    message:
      '确定要删除当前数据吗?',
  })
    .then(() => {
      // on confirm
      jsondata.value?.bodydata[bodyDataName].splice(index, 1)
    })
    .catch(() => {
      // on cancel
    });





}


function handleSelectedSlor(datamodel) {
  // console.log("&&&&",datamodel)
  for (let groupindex in jsondata.value.head) {
    let itemgroup = jsondata.value.head[groupindex].groupvalue
    for (let itemindex in itemgroup) {
      let itemdata = itemgroup[itemindex]
      if (itemdata.sField === 'sname') {
        itemdata.value = datamodel.sname
      } else if (itemdata.sField === 'sheng') {
        itemdata.valuehidden = datamodel.idsheng
        itemdata.value = datamodel.shengRef
      } else if (itemdata.sField === 'shi') {
        itemdata.valuehidden = datamodel.idshi
        itemdata.value = datamodel.shiRef
      } else if (itemdata.sField === 'emterritory') {
        itemdata.valuehidden = datamodel.idquxian
        itemdata.value = datamodel.quxianRef
      } else if (itemdata.sField === 'saddress') {
        itemdata.value = datamodel.saddress
      } else if (itemdata.sField === 'swebsite') {
        itemdata.value = datamodel.swebsite
      } else if (itemdata.sField === 'stel') {
        itemdata.value = datamodel.stel
      } else if (itemdata.sField === 'spostcode') {
        itemdata.value = datamodel.spostcode
      } else if (itemdata.sField === 'jyzt') {
        itemdata.value = datamodel.regstatus
      } else if (itemdata.sField === 'hospgrade') {
        itemdata.valuehidden = datamodel.hospgrade
        itemdata.value = datamodel.hospgrade_enum
      } else if (itemdata.sField === 'idparent') {
        itemdata.value = datamodel.sjkh
      } else if (itemdata.sField === 'yytype') {
        itemdata.value = datamodel.yylx
      } else if (itemdata.sField === 'khsx') {
        itemdata.valuehidden = datamodel.khsx
        itemdata.value = datamodel.khsxEnum
      } else if (itemdata.sField === 'idclientall') {
        itemdata.valuehidden = datamodel.id
        itemdata.value = datamodel.sname
      }
    }
  }

}
</script>

<style scoped>
.L-table-row {
  width: 100%;
  display: flex;
  overflow: scroll;
  border-bottom: 1px solid #efefef;
}

.L-table-row .L-th {
  width: 170px;
  height: 40px;

  flex-grow: 0;
  flex-shrink: 0;
  background-color: #f8f8f8;
  box-sizing: border-box;
  padding-left: 10px;

  display: flex;
  justify-content: flex-start;
  align-items: center;

}

.L-table-row .L-td {
  width: 170px;
  height: 50px;
  flex-grow: 0;
  flex-shrink: 0;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  box-sizing: border-box;
  padding-left: 10px;

}
</style>